package com.fjl.client.config;

import com.fjl.mapper.ChatMessageMapper;
import com.fjl.message.ChatMessage;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class MySqlMemory implements ChatMemory {
    @Autowired
    private ChatMessageMapper chatMessageMapper;
 
    @Override
    public void add(String conversationId, Message message) {
        ChatMessage chatMessage = new ChatMessage();
        // 会话ID
        chatMessage.setConversationId(conversationId);
        // 消息类型
        chatMessage.setRole(message.getMessageType().name());
        // 消息内容
        chatMessage.setContext(message.getText());
        // 插入消息
        chatMessageMapper.insert(chatMessage);
    }
 
    @Override
    public void add(String conversationId, List<Message> messages) {
        messages.stream().forEach(m -> {
            add(conversationId, m);
        });
    }

    @Override
    public List<Message> get(String conversationId) {
        List<ChatMessage> chatMessageList = chatMessageMapper.selectByConversationId(conversationId);

        return chatMessageList.stream()
                .map(c -> {
                    if ("USER".equalsIgnoreCase(c.getRole())) {
                        return new UserMessage(c.getContext());
                    } else if ("ASSISTANT".equalsIgnoreCase(c.getRole()) || "AI".equalsIgnoreCase(c.getRole())) {
                        return new AssistantMessage(c.getContext());
                    } else {
                        // 可选：处理系统消息、Tool 调用、系统角色
                        return new SystemMessage("[未知角色] " + c.getContext());
                    }
                })
                .collect(Collectors.toList());
    }

 
    @Override
    public void clear(String conversationId) {
        chatMessageMapper.delete(conversationId);
    }
}